﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using MSWord = Microsoft.Office.Interop.Word;
using MSExcel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Data;
using System.Data.OleDb;

namespace Web.Admin.ashx
{
    /// <summary>
    /// ajax 的摘要说明
    /// </summary>
    public class ajax : Evan.WebUI.ManagerAshxHelper
    {


        public override void ProcessRequest(HttpContext context)
        {
            string action = Evan.Common.CommFun.GetQueryString("action");
            //OutPutExLog(context);
            //ReadDoc2Html(context);
            if (!IsAdminLogin())
            {
                if (action == "adminLogin")
                {
                    AdminLogin(context);
                }
                else
                {
                    JsonResult(context, -99, "管理员未登陆");
                }
            }
            else
            {
                switch (action)
                {
                    case "memexlog":
                        OutPutExLog(context);
                        break;
                    case "restart":
                        ReStartSite(context);
                        break;
                    case "loaddbschema":
                        MultiDbSchema(context);
                        break;
                    case "exportexcel":
                        ExportExcel(context);
                        break;
                    case "savetemplate":
                        EditTemplate(context);
                        break;
                    case "savesiteconfig":
                        SaveSiteConfig(context);
                        break;
                    case "closedevmode":
                        ChangeConfigMode(context, "dev");
                        break;
                    case "closemodulemode":
                        ChangeConfigMode(context, "module");
                        break;
                    case "generateurl":
                        GenerateUrl(context);
                        break;
                    case "filePathimport":
                        filePathimport(context);
                        break;
                    default:
                        JsonResult(context, -9999, "操作无效");
                        break;
                }
            }
        }

        /// <summary>
        /// 后台債券交易导入
        /// </summary>
        private void filePathimport(HttpContext context)
        {
            try
            {
                if (!Evan.Member.Administrator.IsSuperAdmin())
                {
                    JsonResult(context, -100, "权限不足 , 仅超级管理员可操作");
                }

                string FilePath = GetParam("FilePath");
                Import(HttpContext.Current.Server.MapPath("/") + FilePath);

            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 导入文件中的净值数据
        /// </summary>
        private void Import(string FilePath)
        {
            try
            {

                var Faq = new Evan.DataBase.DbOperat("Faq");
                List<dynamic> FaqList = Faq.GetList_1(0, " states=1 and ClassId=118", Evan.Template.TemplateHelper.GetSqlOrderStr(118));
                int count = 0;
                int SuccessCount = 0;
                try
                {
                    DataTable ExcelDt = GetExeclDS(FilePath);
                    if (ExcelDt != null)
                    {
                        count = ExcelDt.Rows.Count - 1;
                        for (int i = 0; i < ExcelDt.Rows.Count; i++)
                        {
                            if (i < 37)//排除掉excel前面无用部分
                            {
                                continue;
                            }
                            if (string.IsNullOrEmpty(ExcelDt.Rows[i][0].ToString().Trim()))
                                break;
                            dynamic model = new Evan.Model.DynamicModel();
                            var FundModel = FaqList.Find(r => r.SubTitle == ExcelDt.Rows[i][0].ToString().Trim());
                            if (FundModel == null)
                            {
                                //model.Set("Title", FundModel.Title);
                                model.Set("Title", ExcelDt.Rows[i][2].ToString().Trim());
                                model.Set("SubTitle", ExcelDt.Rows[i][0].ToString().Trim());
                                model.Set("Industry", ExcelDt.Rows[i][3].ToString().Trim());
                                model.Set("Coupon", ExcelDt.Rows[i][4].ToString().Trim());
                                try
                                {
                                    model.Set("ExpiryDate", Convert.ToDateTime(ExcelDt.Rows[i][5].ToString().Trim() + " 00:00:00"));
                                }
                                catch
                                {
                                    model.Set("ExpiryDate", new DateTime(1900, 1, 1));
                                }
                                model.Set("Reference", ExcelDt.Rows[i][6].ToString().Trim());
                                model.Set("ReferenceRate", ExcelDt.Rows[i][7].ToString().Trim());
                                model.Set("Currency", ExcelDt.Rows[i][11].ToString().Trim());
                                model.Set("SpeculationLevel", ExcelDt.Rows[i][12].ToString().Trim());
                                model.Set("Professional", ExcelDt.Rows[i][16].ToString().Trim());
                                model.Set("Complex", ExcelDt.Rows[i][17].ToString().Trim());
                                model.Set("RiskScore", ExcelDt.Rows[i][18].ToString().Trim());
                                model.Set("ClassId", 118);
                                model.Set("States", 1);
                                Faq.InsertReturnId(model);
                                SuccessCount += 1;
                            }
                            else
                            {
                                FundModel.Set("Title", ExcelDt.Rows[i][2].ToString().Trim());
                                FundModel.Set("Industry", ExcelDt.Rows[i][3].ToString().Trim());
                                FundModel.Set("Coupon", ExcelDt.Rows[i][4].ToString().Trim());
                                FundModel.Set("ExpiryDate", ExcelDt.Rows[i][5].ToString().Trim());
                                FundModel.Set("Reference", ExcelDt.Rows[i][6].ToString().Trim());
                                FundModel.Set("ReferenceRate", ExcelDt.Rows[i][7].ToString().Trim());
                                FundModel.Set("Currency", ExcelDt.Rows[i][11].ToString().Trim());
                                FundModel.Set("SpeculationLevel", ExcelDt.Rows[i][12].ToString().Trim());
                                FundModel.Set("Professional", ExcelDt.Rows[i][16].ToString().Trim());
                                FundModel.Set("Complex", ExcelDt.Rows[i][17].ToString().Trim());
                                FundModel.Set("RiskScore", ExcelDt.Rows[i][18].ToString().Trim());
                                FundModel.Set("States", 1);
                                Faq.Update(FundModel);
                                SuccessCount += 1;
                            }

                        }
                    }
                    File.Delete(FilePath);
                }
                catch (Exception ex)
                {
                    //Evan.SystemLog.MemLog.AddExLog2("导入文件中的净值数据 执行错误", null, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + ex.Message.ToString());
                }

            }
            catch (Exception ex)
            {
                //Evan.SystemLog.MemLog.AddExLog2("导入文件中的净值数据 执行错误", null, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff") + ex.Message.ToString());
            }


        }


        private static DataTable GetExeclDS(String excelPath)
        {
            try
            {
                string constrr = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + excelPath + ";Extended Properties='Excel 12.0;HDR=No; IMEX=1;'";
                OleDbConnection excelConn = new OleDbConnection(constrr);
                excelConn.Open();
                System.Data.DataTable dt = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                //string tname = dt.Rows[0]["TABLE_NAME"].ToString();
                //if (tname == "Documents_array")
                //{
                //    tname = dt.Rows[1]["TABLE_NAME"].ToString();
                //}
                string tname = "只有中文$";
                string sqqld = "SELECT * FROM [" + tname + "] ";
                OleDbDataAdapter da = new OleDbDataAdapter(sqqld, excelConn);
                DataSet dss = new DataSet();
                da.Fill(dss);
                excelConn.Close();
                return dss.Tables[0];

            }
            catch
            {
                string constrr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelPath + ";Extended Properties='Excel 8.0;HDR=No; IMEX=1;'";
                OleDbConnection excelConn = new OleDbConnection(constrr);
                excelConn.Open();
                System.Data.DataTable dt = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                //string tname = dt.Rows[0]["TABLE_NAME"].ToString();
                string tname = "只有中文$";
                string sqqld = "SELECT  * FROM [" + tname + "] ";
                OleDbDataAdapter da = new OleDbDataAdapter(sqqld, excelConn);
                DataSet dss = new DataSet();
                da.Fill(dss);
                excelConn.Close();
                return dss.Tables[0];

            }


        }

        /// <summary>
        /// 生成全部伪静态链接
        /// </summary>
        /// <param name="context"></param>
        private void GenerateUrl(HttpContext context)
        {
            var list = new Evan.DataBase.DbOperat("Channel").GetList("States=1").ToList();

            foreach (var item in list)
            {
                AutoRewriteAdd(context, item);
            }

            JsonResult(context, 1, "操作成功！");
        }

        /// <summary>
        /// 输出日志
        /// </summary>
        /// <param name="context"></param>
        public void OutPutExLog(HttpContext context)
        {
            string ExLogTxt = Evan.SystemLog.MemLog.GetExLogTxt2();
            byte[] byteArray = null;
            string FileName = "SmartaCMS-SysLog-" + DateTime.Now.ToString("yyyyMMddHHmmssms") + ".txt";
            if (!string.IsNullOrEmpty(ExLogTxt))
            {
                byteArray = System.Text.Encoding.Default.GetBytes(ExLogTxt);
            }
            else
            {
                byteArray = System.Text.Encoding.Default.GetBytes("暂无日志可输出");
            }
            Evan.SystemLog.SysLog.AddSysLog("日志输出", "输出日志 , 文件名" + FileName);
            context.Response.ContentType = "application/octet-stream";
            context.Response.ContentEncoding = System.Text.Encoding.Unicode;
            context.Response.AddHeader("Content-Disposition ", "attachment;filename=" + FileName);
            context.Response.Charset = "GB2312";
            context.Response.OutputStream.Write(byteArray, 0, byteArray.Length);
            context.Response.End();
        }

        /// <summary>
        /// 重启站点
        /// </summary>
        /// <param name="content"></param>
        public void ReStartSite(HttpContext context)
        {
            Evan.Common.CommFun.ReStartCurWeb();
            JsonResult(context, 1, "重启成功");
        }

        /// <summary>
        /// 重载数据库
        /// </summary>
        /// <param name="content"></param>
        public void MultiDbSchema(HttpContext context)
        {
            //new Evan.DataBase.DbSchema().MultiDbSchema();
            JsonResult(context, 1, "重载成功");
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="content"></param>
        public void ExportExcel(HttpContext context)
        {
            int ClassId = int.Parse(GetParam("ClassId"));
            int curPage = 0;
            string WhereStr = "";

            string _temp_curpage = GetParam("curPage");
            if (!string.IsNullOrEmpty(_temp_curpage))
            {
                curPage = int.Parse(_temp_curpage);
            }
            string _temp_title = GetParam("title");
            if (!string.IsNullOrEmpty(_temp_title))
            {
                //暂时只支持按照标题搜索的结果
                WhereStr = string.Format("Title like '%{0}%'", _temp_title);
            }
            Evan.Common.ExportExcel.ExportData(ClassId, curPage, WhereStr);
        }

        /// <summary>
        /// 编辑模板
        /// </summary>
        /// <param name="content"></param>
        public void EditTemplate(HttpContext context)
        {
            try
            {
                if (!Evan.Member.Administrator.IsSuperAdmin())
                {
                    JsonResult(context, -100, "权限不足 , 仅超级管理员可操作");
                }
                //拿到路径
                //拿到内容
                //将现有文件另存为一份备份
                //将内容存储到现有文件
                string ModelStr = GetParam("model");
                string Table = GetParam("table");
                string Id = GetParam("id");
                string Type = GetParam("type");
                dynamic Model = Evan.Model.ConvertModel.ConvertToDynamic(ModelStr);
                string old_content = Evan.Common.DirFile.ReadFile(Model.FilePath);
                string old_path = Model.FilePath + "." + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".bak";
                //将old_content 存储为备份文件
                Evan.Common.DirFile.SaveFile(old_content, old_path);
                //将新的文件覆盖存储
                Evan.Common.DirFile.SaveFile(Model.FileContent, Model.FilePath);
                //写日志
                Evan.SystemLog.SysLog.AddSysLog("管理员 [" + Evan.Member.Administrator.GetAdminName() + "] 修改" + (Type == "Template" ? "模板" : "组件") + "文件成功 , 模板编号 : " + Id, "修改类型 : " + (Type == "Template" ? "模板" : "组件") + "<br/>文件名 : " + Model.FilePath + "<br/>" + "备份文件名 : " + old_path);
                //返回
                JsonResult(context, 1, "成功");
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception ex)
            {
                Evan.SystemLog.MemLog.AddExLog2("编辑模板/组件失败", null, ex.ToString());
                Evan.SystemLog.SysLog.AddSysLog("管理员 [" + Evan.Member.Administrator.GetAdminName() + "] 修改模板/组件文件失败", "管理员 [" + Evan.Member.Administrator.GetAdminName() + "] 修改模板/组件文件失败");
                JsonResult(context, -1, "修改失败 , 请稍后重试");
            }
        }

        /// <summary>
        /// 保存站点配置文件
        /// </summary>
        /// <param name="context"></param>
        public void SaveSiteConfig(HttpContext context)
        {
            try
            {
                if (!Evan.Member.Administrator.IsSuperAdmin())
                {
                    JsonResult(context, -100, "权限不足 , 仅超级管理员可操作");
                }
                dynamic model = Evan.Model.ConvertModel.ConvertToDynamic(GetParam("model"));
                Dictionary<string, object> dic = Evan.Model.ConvertModel.ConvertToDictionary(model);

                string ConfigPath = "~/App_Data/SysConfig/system.config";
                List<dynamic> itemList = new List<dynamic>();
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(Evan.Common.DirFile.ReadFile(ConfigPath));
                XmlNodeList xn = xmldoc.SelectNodes(string.Format("/root/category/item"));

                foreach (XmlElement el in xn)//读元素值
                {
                    el.InnerText = dic[el.Attributes["name"].Value].ToString();
                }
                xmldoc.Save(context.Server.MapPath(ConfigPath));

                Evan.SystemLog.SysLog.AddSysLog("管理员 [" + Evan.Member.Administrator.GetAdminName() + "] 修改 [系统配置] 成功", "修改系统配置成功 [用户名=" + Evan.Member.Administrator.GetAdminName() + "]  ");
                JsonResult(context, 1, "修改成功");
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception ex)
            {
                Evan.SystemLog.MemLog.AddExLog2("修改系统配置失败", null, ex.ToString());
                Evan.SystemLog.SysLog.AddSysLog("管理员 [" + Evan.Member.Administrator.GetAdminName() + "] 添加 [系统配置] 失败", "修改系统配置失败 [用户名=" + Evan.Member.Administrator.GetAdminName() + "]  ");
                JsonResult(context, -1, "修改失败 , 请稍后重试");
            }

        }

        /// <summary>
        /// 改变配置模式
        /// <para>目前支持  开发者模式/模块模式  的开关 </para>
        /// </summary>
        /// <param name="context"></param>
        /// <param name="t">dev 开发者模式 ,  module  模块模式</param>
        private void ChangeConfigMode(HttpContext context, string t)
        {
            if (t == "dev")
            {
                Evan.Config.WebConfig.EditAppSetting("DevMode", "0");
            }
            if (t == "module")
            {
                Evan.Config.WebConfig.EditAppSetting("IsModuleSystem", "0");
            }
            JsonResult(context, 1, "关闭成功");
        }


        public void ReadDoc2Html(HttpContext context)
        {

            Object Path = context.Server.MapPath("~/123.docx");
            Object Nothing = Missing.Value;
            object format = MSWord.WdSaveFormat.wdFormatFilteredHTML;
            MSWord.Application wordApp = new MSWord.ApplicationClass();
            MSWord.Document wordDoc = wordApp.Documents.Open(ref Path, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref format, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            //StringBuilder sb = new StringBuilder();
            //foreach (var item in wordDoc.Paragraphs)
            //{
            //    sb.Append(item.)
            //}
            string temp = wordDoc.Paragraphs[1].Range.Text.Trim();

            string a = temp;

        }


    }
}